﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using com.dz.common;
using com.dz.components;
using System.Text;
using com.dz.httpmoudle;
namespace com.dz.web
{
    public class PageUtil
    {
        /// <summary>
        /// 用户登录Token
        /// </summary>
        public static UserToken Token
        {
            get
            {
                UserToken token = HttpContext.Current.Items[AuthenticateModule.CONTEXT_ROLE_KEY] as UserToken;
                return token;
            }

        }
        /// <summary>
        /// 执行脚本
        /// </summary>
        /// <param name="procName"></param>
        /// <param name="script"></param>
        /// <returns></returns>
        public static string ExcuteScript(string i_proc_name, string i_script)
        {
            if (string.IsNullOrEmpty(i_proc_name) || string.IsNullOrEmpty(i_script))
                return "参数错误";

            string t_result = "操作失败";
            BookCommendManager t_book_commend_mgr = new BookCommendManager();
            BookManager t_book_mgr = new BookManager();
            switch (i_proc_name)
            {
                case "首页封推":
                    
                    t_result = t_book_commend_mgr.AddBookCommendByBookId(i_script, Consts.CommendType.ICON);
                    break;
                case "取消首页封推":
                   
                    t_result = t_book_commend_mgr.DeleteBookComendByBookId(i_script, Consts.CommendType.ICON);
                    break;
                case "重磅推荐":
                    t_result = t_book_commend_mgr.AddBookCommendByBookId(i_script, Consts.CommendType.IMPORTANCE);
                    break;
                case "VIP推荐":
                    t_result = t_book_commend_mgr.AddBookCommendByBookId(i_script, Consts.CommendType.VIP);
                    break;
                case "男生精选":
                    t_result = t_book_commend_mgr.AddBookCommendByBookId(i_script, Consts.CommendType.Boy);
                    break;
                case "女生精选":
                    t_result = t_book_commend_mgr.AddBookCommendByBookId(i_script, Consts.CommendType.Girl);
                    break;
                case "本类推荐":
                    t_result = t_book_mgr.AddBookCategoryCommend(i_script);
                    break;
                case "章节缺省":
                    BookChapterManager t_book_chapter_mgr = new BookChapterManager();
                    t_result = t_book_chapter_mgr.UpdateChapterStatus(i_script);
                    break;
                case "review":
                    long t_user_id = 0;
                    if (Token != null)
                    {
                        t_user_id = Token.UserId;
                    }
                    t_result = t_book_mgr.InsertReview(i_script, t_user_id);
                    break;
                case "register":
                    UserManager t_user_mgr = new UserManager();
                   t_result=  t_user_mgr.RegisterUser(i_script);
                    break;
                case "chapter":
                    t_result = GetChapterUrl(i_script);
                    break;
                case "login":
                    UserManager u_mgr=new UserManager();
                    t_result = u_mgr.UserLogin(i_script);
                    break;
                case "bookcase":
                     t_result = AddUserBook(i_script,Consts.BookType.BookCase);
                    break;
                case "bookcommend":
                    t_result = AddUserBook(i_script, Consts.BookType.BookCommend);
                    break;
                case "updateuserinfo":
                   t_result= UpdateUser(i_script);
                    break;
                case "contactus":
                    t_result = ContactUS(i_script);
                       break;
                case "loginout":
                       UserLoginHelper.DeleteUserTicket();
                       t_result = "成功退出";
                    break;
                case "updatebook":
                  t_result=  t_book_mgr.UpdateBookRequest(i_script);
                       break;
            }
            return t_result;
        }

        /// <summary>
        /// 联系我们
        /// </summary>
        /// <param name="i_script"></param>
        /// <returns></returns>
        private static string ContactUS(string i_script)
        {
 
            if(string.IsNullOrEmpty(i_script))
                return "参数错误!";
            string[] t_arr=i_script.Split(new char[]{'$'},StringSplitOptions.RemoveEmptyEntries);
            if(t_arr==null ||t_arr.Length!=5)
                return "参数错误!";
            string email=t_arr[0].ToString();
            string qq=t_arr[1].ToString();
            string telephone=t_arr[2].ToString();
            int t_contactType=0;
            if(!int.TryParse(t_arr[3].ToString(),out t_contactType))
                t_contactType=0;
            string content=t_arr[4].ToString();

            long t_user_id = 0;
            if (Token != null)
                t_user_id = Token.UserId;

            UserManager t_user_mgr = new UserManager();
            try
            {
                int t_ret = t_user_mgr.AddContactUS(t_user_id, t_contactType, content, telephone, qq, email);
                if (t_ret > 0)
                    return "信息添加成功,我们会尽快与你联系!";
                return "添加失败!";
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加联系我们信息失败" + ex.ToString());
                return "程序出现异常,请稍后重试!";
            }
        }

        private static string UpdateUser(string i_script)
        {
            if (string.IsNullOrEmpty(i_script))
                return "参数错误!";
            string[] t_arr = i_script.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
            if (t_arr == null || t_arr.Length != 2)
                return "参数错误!";

            if (Token == null)
            {
                return "登录信息已经丢失，请重新登录!";
            }

            UserManager t_user_mgr = new UserManager();
            try
            {
                int t_ret = t_user_mgr.UpdateUser(Token.UserId, t_arr[0].ToString(), t_arr[1].ToString());
                if (t_ret > 0)
                    return "修改成功!";
                return "操作失败,请稍后重试!";
            }
            catch (Exception ex)
            {
                LogHelper.Error("更新用户资料失败" + ex.ToString());
                return "程序异常,请稍后重试!";
            }
        }

        /// <summary>
        /// 添加用户书籍
        /// </summary>
        /// <param name="i_script"></param>
        /// <param name="i_book_type"></param>
        /// <returns></returns>
        private static string AddUserBook(string i_script, Consts.BookType i_book_type)
        {
            if(Token==null)
                return "你还没登录,请先登录!";
            long t_book_id = 0;
            if (!long.TryParse(i_script, out t_book_id))
                t_book_id = 0;
            long t_user_id = Token.UserId;

            if (t_book_id == 0)
                return "参数错误!";
 

            BookManager t_user_mgr = new BookManager();
            try
            {
                int t_ret = t_user_mgr.AddUserBook(t_user_id, t_book_id, (int)i_book_type);
                if (t_ret > 0)
                    return "操作成功!";
                return "操作失败";
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加用户书籍失败" + ex.ToString());
                return "程序异常,请稍后重试!";
            }
        }

        private static string GetChapterUrl(string i_script)
        {
            if (string.IsNullOrEmpty(i_script))
                return "/Error.aspx";

            string[] arr = i_script.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);

            if(arr==null || arr.Length!=3)
                return "/Error.aspx";

            string t_key = arr[2];

           if(SystemUtil.MD5Mac(string.Format("{0},{1},@!rjgod",  arr[0], arr[1]))!=t_key)
               return "/Error.aspx";

           long t_book_id = 0;

           //更新点击
           if (CookieManager.GetBookReadCount(t_book_id))
           {
               BookManager t_book_mgr = new BookManager();

               t_book_mgr.UpdateBookTopParams(t_book_id, 1);
           }
            return string.Format("{0}/{1}/{2}.txt", AppConfig.FileServer, arr[0], arr[1]);
        }


        /// <summary>
        /// 分页获取列表页小说列表
        /// </summary>
        /// <param name="i_page_index"></param>
        /// <param name="i_page_size"></param>
        /// <param name="i_total_count"></param>
        /// <param name="i_str_where"></param>
        /// <returns></returns>
        public static string GetChannelBook(int i_page_index, int i_page_size, int i_total_count, string i_str_where)
        {
            if (string.IsNullOrEmpty(i_str_where))
                return string.Empty;

            string[] t_arr = i_str_where.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
            if (t_arr == null || t_arr.Length != 2)
                return string.Empty;

            Consts.BookOrderType t_order = Consts.BookOrderType.Click;
            if (t_arr[1].ToString().Equals("1"))
                t_order = Consts.BookOrderType.Click;
            else if (t_arr[1].ToString().Equals("2"))
                t_order = Consts.BookOrderType.Collect;
            else if (t_arr[1].ToString().Equals("3"))
                t_order = Consts.BookOrderType.UpdateTime;
            else
                t_order = Consts.BookOrderType.WordsCount;
               BookManager t_book_mgr = new BookManager();
            int t_total_count=0;
            DataSet ds = t_book_mgr.GetChannelBookList(t_arr[0].ToString(), t_order, i_page_index, i_page_size, out t_total_count);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
                return string.Empty;

            if (t_total_count == 0)
                t_total_count = i_total_count;

            System.Text.StringBuilder t_sb = new System.Text.StringBuilder();

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                t_sb.AppendFormat("var totalCount={0};", t_total_count);
                t_sb.AppendFormat("var list=new Array({0});", ds.Tables[0].Rows.Count);
                string t_des = string.Empty;

                for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                {
                    // bookId,bookName,bookCategoryName,bookSubCategoryName,[description],click,collect,lastUpdateChapterId,lastUpdateChapterName,authorName 

                    t_sb.AppendFormat("list[{0}]=new Array('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}');", index,
                        ds.Tables[0].Rows[index]["bookId"],
                        ds.Tables[0].Rows[index]["bookName"],
                        ds.Tables[0].Rows[index]["bookCategoryName"],
                        ds.Tables[0].Rows[index]["bookSubCategoryName"],
                       SystemUtil.GetGBString( ds.Tables[0].Rows[index]["description"].ToString().ToLower().Replace("'", "").Replace("\"", "").Replace("<div>","<br>").Replace("</div>","").Replace("&nbsp;"," "),80),
                        ds.Tables[0].Rows[index]["click"],
                        ds.Tables[0].Rows[index]["collect"],
                        ds.Tables[0].Rows[index]["lastUpdateChapterId"],
                        ds.Tables[0].Rows[index]["lastUpdateChapterName"].ToString().Replace("'", "").Replace("\"", ""),
                        ds.Tables[0].Rows[index]["authorName"]
                        );
                }
            }
            t_sb.Append(GetPagerBar(i_page_index, i_page_size, t_total_count));

            return t_sb.ToString();

        }


        /// <summary>
        /// ajax分页
        /// </summary>
        /// <param name="i_page_index"></param>
        /// <param name="i_page_size"></param>
        /// <param name="i_str_where"></param>
        /// <returns></returns>
        public static string GetList(int i_page_index, int i_page_size,int i_total_count, string i_str_where)
        {
            long t_book_id = 0;
            if (!long.TryParse(i_str_where, out t_book_id))
                t_book_id = 0;
            if (t_book_id == 0)
                return string.Empty;

            int o_total_count = 0;

            BookManager t_book_mgr = new BookManager();
            System.Text.StringBuilder t_sb = new System.Text.StringBuilder();

           
            try
            {
                //更新点击
                if (CookieManager.GetBookReadCount(t_book_id))
                {
                    t_book_mgr.UpdateBookTopParams(t_book_id, 1);
                }


                DataSet t_ds = t_book_mgr.GetBookReview(-1, t_book_id, i_page_index, i_page_size, out o_total_count);

                if (o_total_count == 0)
                    o_total_count = i_total_count;

                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    t_sb.AppendFormat("var totalCount={0};", o_total_count);
                    t_sb.AppendFormat("var list=new Array({0});", t_ds.Tables[0].Rows.Count);
                    for (int index = 0; index < t_ds.Tables[0].Rows.Count; index++)
                    {
                        t_sb.AppendFormat("list[{0}]=new Array('{1}','{2}','{3}');", index, t_ds.Tables[0].Rows[index]["userName"], t_ds.Tables[0].Rows[index]["createtime"], t_ds.Tables[0].Rows[index]["reviewContent"].ToString().Replace("'","").Replace("\"",""));
                    }
                }
                t_sb.Append(GetPagerBar(i_page_index, i_page_size, o_total_count));

                return t_sb.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取分页数据失败" + ex.ToString());
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取分页条码
        /// </summary>
        /// <param name="i_page_index">请求的页码</param>
        /// <param name="i_total_page_count">总共多少页，为了减少数据库压力，通常在第一页的时候取分页总数</param>
        /// <returns></returns>
        public static string GetPagerBar(int i_page_index,int i_page_size, int i_total_count)
        {

            StringBuilder sb = new StringBuilder();

            int t_total_page_count =i_total_count % i_page_size==0?i_total_count/i_page_size:i_total_count/i_page_size+1;

            if (t_total_page_count <= 1)
                return " var t_pager='';";

            int start = ((i_page_index - 1) / 10) * 10 + 1;
            if (i_page_index > 1)
            {
                sb.AppendFormat("<a href=javascript:GoPage({0}) title=上一页>上一页</a>", (i_page_index - 1));
            }
            for (int i = start; i <= t_total_page_count && i < start + 10; i++)
            {
                if (i == i_page_index)
                    sb.AppendFormat("<span class=current title=当前第{0}页 >{0}</span>", i);
                else
                    sb.AppendFormat("<a href=javascript:GoPage({0}) title=第{0}页>{0}</a>", i);
            }
            if (start > 1)
            {
                sb.Insert(0, String.Format("<a href=javascript:GoPage({0})  title=第{0}页>...</a>",  (start - 1)));
                sb.Insert(0, String.Format("<a href=javascript:GoPage({0})  title=首页>{0}</a>",  1));
            }
            if (start + 10 <= t_total_page_count)
            {
                sb.AppendFormat("<a href=javascript:GoPage({0}) title=第{0}页>...</a>",  (start + 10));
                sb.AppendFormat("<a href=javascript:GoPage({0}) title=第{0}页(末页)>{0}</a>",  t_total_page_count);
            }
            if (t_total_page_count > 1)
            {
                sb.AppendFormat("<a href=javascript:GoPage({0}) title=下一页>下一页</a>", (i_page_index + 1));
            }
            sb.Insert(0, "<div id=pager_blockdd><div id=pager>");
            sb.Append("</div></div>");

            string t_pager = string.Format(" var t_pager='{0}';", sb.ToString());
            return t_pager;

        }
    }
}
